﻿import store from '@/store'
import router from '@/router'

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * @description 将树形结构扁平化
 * @param {tree: Array}
 * @param {props: String}
 * @return Array
 */
export function treeToArray(tree, props = 'children') {
  const res = [] // 接收结果
  while (tree.length) { // 栈不为空则循环执行
    const item = tree[0] // 取出栈顶元素
    res.push(item) // 元素本身压入结果数组
    tree.shift() // 将当前元素弹出栈
    // 逻辑处理，如果当前元素包含子元素，则将子元素压入栈
    if (item[props] && item[props].length) {
      tree.push(...item[props])
    }
  }
  return res
}

/**
 * @description 将扁平化结构转为树
 * @param {list: Array}
 * @param {props: String}
 * @return Array
 */
export function arrayToTree(list, props = 'children') {
  const [map, treeData] = [{}, []]
  for (let i = 0; i < list.length; i += 1) {
    map[list[i].id] = i
    list[i][props] = []
  }
  list.forEach(node => {
    if (node.parentId && list[map[node.parentId]]) {
      list[map[node.parentId]][props].push(node)
    } else {
      treeData.push(node)
    }
  })
  return treeData
}

/**
 * 自定义日期格式转换日期
 * @param {Date} date
 * @param {String} format
 */
export function getTime(date, format = 'YYYY-MM-DD hh:mm:ss') {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()

  format = format.replace('YYYY', year)
  format = format.replace('MM', String(month).padStart(2, '0'))
  format = format.replace('DD', String(day).padStart(2, '0'))
  format = format.replace('hh', String(hours).padStart(2, '0'))
  format = format.replace('mm', String(minutes).padStart(2, '0'))
  format = format.replace('ss', String(seconds).padStart(2, '0'))

  return format
}

// 将驼峰式改为-小写
export function convertToKebabCase(str) {
  const firstChar = str.charAt(0).toLowerCase()
  const restOfChars = str.slice(1)

  const kebabCaseRest = restOfChars.replace(/[A-Z]/g, (match) => {
    return '-' + match.toLowerCase()
  })
  return firstChar + kebabCaseRest
}

// 跳转页面
export function openPage(title, url, params) {
  const obj = { path: url, meta: { title: title }}
  store.dispatch('tagsView/addView', obj)
  return router.push({ path: url, query: params })
}

// 处理路由返回地址
export function toLastView(visitedViews, view) {
  const activeMenu = view.meta.activeMenu
  const rows = activeMenu ? visitedViews.find(item => item.path === activeMenu) : false
  const latestView = visitedViews.slice(-1)[0]
  if (activeMenu && rows) {
    router.push(activeMenu)
  } else if (latestView) {
    router.push(latestView.fullPath)
  } else {
    if (view.name === 'Home') {
      router.replace({ path: '/redirect' + view.fullPath })
    } else {
      router.push('/')
    }
  }
}

// 防抖方法，针对频繁触发的函数取最后一次
export function debounce(fn, delay = 500) {
  let timer
  return function() {
    const content = this
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(content, arguments)
    }, delay)
  }
}
